module("ufe.policies.list", package.seeall)
local m = require("ufe.ufe_module")
local conf = require("ufe.config")
local u = require("ufe.util.update")

local action = "list"

local function check(acf)
    if type(acf.value) ~= 'table' then
        return false, 'wrong value format in list action'
    end

    local ok, err = u.check(acf)
    if not ok then
        return false, err.." in list action"
    end

    if acf.nameList and type(acf.nameList) ~= 'table' then
        return false, 'wrong nameList format in list action'
    end

    local v = m.get_value_handler(acf.value.type)
    if not v then
        return false, 'Not find or support value type in list action'
    end

    if not v.check then return true end

    return  v.check(acf.value)
end


local function execute(acf, key, id)
    local vh = m.get_value_handler(acf.value.type)

    local value = vh.value(acf.value)
    if not value then return false end

    --check if value in default nameList
    if acf.nameList then
        for _, v in ipairs(acf.nameList) do
            if value == v then return true end
        end
    end

    key = key .. value
    local result = u.get(key, acf)

    if not result then return false end

    if result == "B"..id then return true end

    return false

end

m.register_policy(action, {check = check, execute = execute })
